package com.xingdata.jjxc.m.avt;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnInfoWindowClickListener;
import com.amap.api.maps.AMap.OnMapClickListener;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.Inputtips.InputtipsListener;
import com.amap.api.services.help.Tip;
import com.xingdata.jjxc.R;
import com.xingdata.jjxc.utils.Log;

public class ComAddressMapavt extends Activity implements LocationSource,
		AMapLocationListener, OnMapClickListener, OnGeocodeSearchListener,
		TextWatcher, OnItemClickListener, OnClickListener, InfoWindowAdapter,
		OnInfoWindowClickListener {
	private TextView com_find_map_tv;

	private String TAG = "TestActivity";
	private AMap aMap;
	private MapView mapView;
	private OnLocationChangedListener mListener;
//	private LocationManagerProxy mAMapLocationManager;
	// 搜索框
	private AutoCompleteTextView serchEditText;
	// 搜索适配器
	private ArrayAdapter serchAdapter;
	// 搜索重新封装的数据
	private List<Tip> tips = null;
	private Bundle mBundle;
	// 适配器中的数据
	private List<String> adaList = new ArrayList<String>();
	private View pop_view;
	// // ---------------------变量---------------------
	// private String[] mStrategyMethods;// 记录行车策略的数组
	// private String[] mPositionMethods;// 记录起点我的位置、地图点选数组
	// // 驾车路径规划起点，途经点，终点的list
	// private List<NaviLatLng> mStartPoints = new ArrayList<NaviLatLng>();
	// private List<NaviLatLng> mWayPoints = new ArrayList<NaviLatLng>();
	private List<NaviLatLng> mEndPoints = new ArrayList<NaviLatLng>();
	// // 记录起点、终点、途经点位置
	private NaviLatLng mStartPoint = new NaviLatLng();
	private NaviLatLng mEndPoint = new NaviLatLng();
	// private NaviLatLng mWayPoint = new NaviLatLng();

	// // 记录起点、终点、途经点在地图上添加的Marker
	private Marker mStartMarker;
	private Marker mWayMarker;
	private Marker mEndMarker;
	private Marker mGPSMarker;
	// private boolean mIsGetGPS = false;// 记录GPS定位是否成功
	// private boolean mIsStart = false;// 记录是否已我的位置发起路径规划
	// private PopupWindow navigationPopupWindow = null;
	// 坐标/地名转换
	private GeocodeSearch geocoderSearch;
	// 记录地图点击事件相应情况，根据选择不同，地图响应不同
	private int mMapClickMode = MAP_CLICK_NO;
	private static final int MAP_CLICK_NO = 0;// 地图不接受点击事件
	// private static final int MAP_CLICK_START = 1;// 地图点击设置起点
	// private static final int MAP_CLICK_WAY = 2;// 地图点击设置途经点
	private static final int MAP_CLICK_END = 3;// 地图点击设置终点

	// 传到添加常用地址的界面
	private String addname_seach;
	private String lat_seach, lon_seach;

	/**
	 * 搜索的具体地址
	 */
	private String addressName;
	public static final LatLng ZHENGZHOU = new LatLng(34.7466, 113.625367);// 郑州市经纬度

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_com_address_map_avt);
		mapView = (MapView) findViewById(R.id.bmapView);
		mapView.onCreate(savedInstanceState);
		init();
		initMapAndNavi();
	}

	/**
	 * 初始化地图和导航相关内容
	 */
	private void initMapAndNavi() {
		// 初始化Marker添加到地图
		mStartMarker = aMap.addMarker(new MarkerOptions()
				.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
						.decodeResource(getResources(), R.drawable.start))));
		mWayMarker = aMap.addMarker(new MarkerOptions()
				.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
						.decodeResource(getResources(), R.drawable.way))));
		// 动画效果
		ArrayList<BitmapDescriptor> giflist = new ArrayList<BitmapDescriptor>();
		// giflist.add(BitmapDescriptorFactory
		// .defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
		giflist.add(BitmapDescriptorFactory
				.defaultMarker(BitmapDescriptorFactory.HUE_RED));
		// giflist.add(BitmapDescriptorFactory
		// .defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));

		mEndMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
				.position(ZHENGZHOU).title("郑州市").icons(giflist)
				.draggable(true).period(0));
		mGPSMarker = aMap.addMarker(new MarkerOptions()
				.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
						.decodeResource(getResources(),
								R.drawable.location_marker))));
	}

	private void init() {
		com_find_map_tv = (TextView) findViewById(R.id.com_find_map_tv);
		com_find_map_tv.setOnClickListener(this);
		mMapClickMode = MAP_CLICK_END;

		if (aMap == null) {
			aMap = mapView.getMap();
			setUpMap();
		}
		serchEditText = (AutoCompleteTextView) findViewById(R.id.com_search_map_et);
		geocoderSearch = new GeocodeSearch(this);
		// 输入提示的监听接口
		serchEditText.addTextChangedListener(this);
		serchEditText.setOnItemClickListener(this);
		// 地名搜索监听接口
		geocoderSearch.setOnGeocodeSearchListener(this);

		// TTSController ttsManager = TTSController.getInstance(this);// 初始化语音模块
		// ttsManager.init();
		// AMapNavi.getInstance(this).setAMapNaviListener(ttsManager);//
		// 设置语音模块播报

		// geocodeQuery("西直门", "110102");

	}

	/**
	 * 根据地名艘搜索坐标 第一个参数表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode
	 */
	private void geocodeQuery(String address, String cityCode) {
		GeocodeQuery query = new GeocodeQuery(address, cityCode);
		geocoderSearch.getFromLocationNameAsyn(query);
	}

	/**
	 * 根据坐标点搜索地名 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
	 */
	private void regeocodeQuery(LatLonPoint latLonPoint) {
		RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200,
				GeocodeSearch.AMAP);
		geocoderSearch.getFromLocationAsyn(query);
	}

	private void setUpMap() {
		aMap.setLocationSource(this);// 设置定位监听
		aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
		aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
		// 设置定位的类型为定位模式：定位（AMap.LOCATION_TYPE_LOCATE）、跟随（AMap.LOCATION_TYPE_MAP_FOLLOW）
		// 地图根据面向方向旋转（AMap.LOCATION_TYPE_MAP_ROTATE）三种模式
		aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
		aMap.setOnMapClickListener(this);
		aMap.setOnInfoWindowClickListener(this);
		aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
	}

	/**
	 * 定位成功后回调函数
	 */
	@Override
	public void onLocationChanged(AMapLocation amapLocation) {

		if (mListener != null && amapLocation != null) {
			if (amapLocation.getErrorCode() == 0) {
				mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
				mStartPoint.setLatitude(amapLocation.getLatitude());
				mStartPoint.setLongitude(amapLocation.getLongitude());
			}
		}
		// if(amapLocation != null &&
		// amapLocation.getAMapException().getErrorCode() == 0){
		// //获取位置信息
		// Double geoLat = amapLocation.getLatitude();
		// Double geoLng = amapLocation.getLongitude();
		//
		// System.out.println("当前位置坐标：" +geoLat+":"+geoLng);
		// }

	}

	/**
	 * 激活定位
	 */
	@Override
	public void activate(OnLocationChangedListener listener) {
		// mListener = listener;
		// if (mAMapLocationManager == null) {
		// mAMapLocationManager = LocationManagerProxy.getInstance(this);
		// // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
		// // 注意设置合适的定位时间的间隔，并且在合适时间调用removeUpdates()方法来取消定位请求
		// // 在定位结束后，在合适的生命周期调用destroy()方法
		// // 其中如果间隔时间为-1，则定位只定一次
		// mAMapLocationManager.requestLocationData(
		// LocationProviderProxy.AMapNetwork, 60 * 1000, 10, this);
		// }
	}

	/**
	 * 停止定位
	 */
	@Override
	public void deactivate() {
		// mListener = null;
		// if (mAMapLocationManager != null) {
		// mAMapLocationManager.removeUpdates(this);
		// mAMapLocationManager.destroy();
		// }
		// mAMapLocationManager = null;
	}

	/**
	 * 此方法需存在
	 */
	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();
	}

	/**
	 * 此方法需存在
	 */
	@Override
	protected void onPause() {
		super.onPause();
		mapView.onPause();
		deactivate();
	}

	/**
	 * 此方法需存在
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();
	}

	@Override
	public void onMapClick(LatLng latLng) {
		mMapClickMode = MAP_CLICK_NO;
		// 默认不接受任何操作
		if (mMapClickMode == MAP_CLICK_NO) {
			mMapClickMode = MAP_CLICK_END;
			return;
		}
		// 其他情况根据起点、途经点、终点不同逻辑处理不同
		addPointToMap(latLng);
		regeocodeQuery(new LatLonPoint(latLng.latitude, latLng.longitude));
		Log.i(TAG, "latitude:" + latLng.latitude + " longitude:"
				+ latLng.longitude);

	}

	/**
	 * 画出坐标点
	 * 
	 * @param latLng
	 */
	private void addPointToMap(LatLng latLng) {

		NaviLatLng naviLatLng = new NaviLatLng(latLng.latitude,
				latLng.longitude);
		switch (mMapClickMode) {
		// 终点
		case MAP_CLICK_END:
			mEndMarker.setPosition(latLng);
			mEndPoints.clear();
			mEndPoint = naviLatLng;
			mEndPoints.add(mEndPoint);
			mEndMarker.showInfoWindow();// ******
			break;
		}

	}

	@Override
	public void onGeocodeSearched(GeocodeResult result, int rCode) {
		if (rCode == 0) {
			if (result != null && result.getGeocodeAddressList() != null
					&& result.getGeocodeAddressList().size() > 0) {
				GeocodeAddress address = result.getGeocodeAddressList().get(0);
				String addressName = "经纬度值:" + address.getLatLonPoint()
						+ "\n位置描述:" + address.getFormatAddress();

				lat_seach = String.valueOf(address.getLatLonPoint()
						.getLatitude());
				lon_seach = String.valueOf(address.getLatLonPoint()
						.getLongitude());

				addname_seach = address.getFormatAddress()
						+ address.getTownship();
				// 搜索完毕后根据坐标点画出
				addPointToMap(new LatLng(
						address.getLatLonPoint().getLatitude(), address
								.getLatLonPoint().getLongitude()));

				showToast(addname_seach);

			} else {
				showToast("没有搜索到结果");
			}

		} else {
			showToast("网络异常");
		}
	}

	@Override
	public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
		// if (rCode == 0) {
		// if (result != null && result.getRegeocodeAddress() != null
		// && result.getRegeocodeAddress().getFormatAddress() != null) {
		// addressName = result.getRegeocodeAddress().getFormatAddress()
		// + "附近";
		// showToast(addressName);
		// } else {
		// showToast("没有搜索到地址");
		// }
		// } else {
		// showToast("网络异常");
		// }
	}

	private void showToast(String t) {
		Log.i(TAG, t);
		Toast.makeText(ComAddressMapavt.this, t, Toast.LENGTH_LONG).show();
	}

	// 输入信息改变之后
	@Override
	public void afterTextChanged(Editable s) {

	}

	// 输入信息改变之前
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	// 正在输入
	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		String newText = s.toString();
		// 输入信息的回调方法
		Inputtips inputTips = new Inputtips(ComAddressMapavt.this,
				new InputtipsListener() {
					@Override
					public void onGetInputtips(List<Tip> tipList, int rCode) {
						adaList.clear();
						if (tips == null) {
							tips = new ArrayList<Tip>();
						} else {
							tips.clear();
						}
						if (tipList != null) {
							tips.clear();
						}
						tips.addAll(tipList);
						for (Tip tip : tipList) {
							adaList.add(tip.getName());
							Log.i(TAG, "name :" + tip.getName());
						}
						serchAdapter = new ArrayAdapter(
								getApplicationContext(), R.layout.route_inputs,
								adaList);
						serchEditText.setAdapter(serchAdapter);
						serchAdapter.notifyDataSetChanged();
					}
				});

		// 发送输入提示请求
		// 第一个参数表示提示关键字，第二个参数默认代表全国，也可以为城市区号
		try {
			inputTips.requestInputtips(newText, "");
		} catch (com.amap.api.services.core.AMapException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position,
			long id) {
		Log.i(TAG,
				"NAME:" + tips.get(position).getName() + "  District:"
						+ tips.get(position).getDistrict() + " Adcode:"
						+ tips.get(position).getAdcode());
		geocodeQuery(tips.get(position).getName(), tips.get(position)
				.getAdcode());
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.com_find_map_tv:
			finish();
			break;
		case R.id.pop_simulate:

			break;

		default:
			break;
		}
	}

	//
	// @Override
	// public void onLocationChanged(Location location) {
	// // TODO Auto-generated method stub
	//
	// }
	//
	// @Override
	// public void onStatusChanged(String provider, int status, Bundle extras) {
	// // TODO Auto-generated method stub
	//
	// }
	//
	// @Override
	// public void onProviderEnabled(String provider) {
	// // TODO Auto-generated method stub
	//
	// }
	//
	// @Override
	// public void onProviderDisabled(String provider) {
	// // TODO Auto-generated method stub
	//
	// }

	@Override
	public View getInfoContents(Marker marker) {

		View infoContent = getLayoutInflater().inflate(
				R.layout.pop_car_address_set, null);
		return infoContent;
	}

	@Override
	public View getInfoWindow(Marker marker) {

		View infoWindow = getLayoutInflater().inflate(
				R.layout.pop_car_address_set, null);
		// TextView pop_name = ((TextView) infoWindow
		// .findViewById(R.id.pop_company_nameset_tv));
		// TextView pop_address = ((TextView) infoWindow
		// .findViewById(R.id.pop_company_addressset_tv));
		// RelativeLayout pop_address_set_rl = (RelativeLayout) infoWindow
		// .findViewById(R.id.pop_address_set_iv);
		//
		// pop_name.setText(serchEditText.getText().toString());
		//
		// pop_address.setText(addname_seach);
		// pop_address_set_rl.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		//
		// if ("".equals(serchEditText.getText())) {
		// return;
		// }
		// Intent emulatorIntent = new Intent(ComAddressMapavt.this,
		// ComAddressSetavt.class);
		// Bundle bundle = new Bundle();
		//
		// bundle.putSerializable("areaid", serchEditText.getText()
		// .toString());// 地区
		// bundle.putSerializable("address", addname_seach);// 实际地址
		// bundle.putSerializable("longitude", lon_seach);
		// bundle.putSerializable("latitude", lat_seach);
		//
		// emulatorIntent.putExtras(bundle);
		// startActivity(emulatorIntent);
		//
		// }
		// });
		return infoWindow;
	}

	@Override
	public void onInfoWindowClick(Marker marker) {

	}
}
